package com.example.simpleforum.servlet;

import com.example.simpleforum.dao.ForumDao;
import com.example.simpleforum.model.Forum;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/ForumSearchServlet")
public class ForumSearchServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String keyword = request.getParameter("keyword");
        String format = request.getParameter("format");
        ForumDao forumDao = new ForumDao();
        List<Forum> forums = forumDao.searchByName(keyword);
        
        if ("json".equals(format)) {
            // 返回JSON格式数据
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            
            // 简化返回数据
            List<Map<String, Object>> simpleForums = new ArrayList<>();
            for (Forum forum : forums) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", forum.getId());
                map.put("name", forum.getName() != null ? forum.getName() : "");
                map.put("description", forum.getDescription() != null ? forum.getDescription() : "");
                simpleForums.add(map);
            }
            
            // 手动构建JSON字符串
            StringBuilder json = new StringBuilder("[");
            for (int i = 0; i < simpleForums.size(); i++) {
                Map<String, Object> forum = simpleForums.get(i);
                json.append("{")
                    .append("\"id\":").append(forum.get("id"))
                    .append(",\"name\":\"").append(forum.get("name") != null ? forum.get("name").toString().replace("\"", "\\\"") : "")
                    .append("\",\"description\":\"")
                    .append(forum.get("description") != null ? forum.get("description").toString().replace("\"", "\\\"") : "")
                    .append("\"}");
                if (i < simpleForums.size() - 1) {
                    json.append(",");
                }
            }
            json.append("]");
            response.getWriter().write(json.toString());
        } else {
            // 设置请求属性并转发到JSP页面
            request.setAttribute("forums", forums);
            request.setAttribute("keyword", keyword);
            request.getRequestDispatcher("/forumSearchResults.jsp").forward(request, response);
        }
    }
}